package com.qincji.bottombar;

import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ElementScatter;
import ohos.agp.utils.Color;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * description: 底部栏tabbar控件 <br>
 *
 * @author qincji
 * @email xhunmon@126.com
 * @date 2021/6/14
 */
public class TabBar extends DirectionalLayout {

    private int TAB_NUM;//tab的个数
    private OnTabBarClickListener listener;
    private final List<DirectionalLayout> tabLayouts = new ArrayList<>();
    private final List<TabItem> tabItems = new ArrayList<>();
    private int curSelect = 0;//当前选择的条目
    private Element backgroundElement;//底部栏背景颜色
    private int imgWidth;//图标的宽度
    private int imgHeight;//图标的高度
    private Color txtNormalColor;//默认字体未选择颜色
    private Color txtActiveColor;//默认字体未选择颜色
    private int txtSize;//字体大小
    private DirectionalLayout selectLayout;//当前选中的条目


    public TabBar(Context context) {
        this(context, null);
    }

    public TabBar(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public TabBar(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initDefault();
    }

    private void initDefault() {
        backgroundElement = ElementScatter.getInstance(getContext()).parse(ResourceTable.Graphic_tab_background);
        imgWidth = TabUtils.vp2px(getContext(), 24);
        imgHeight = TabUtils.vp2px(getContext(), 24);
        txtNormalColor = new Color(Color.rgb(153, 153, 153));
        txtActiveColor = new Color(Color.rgb(34, 34, 34));
        txtSize = TabUtils.vp2px(getContext(), 10);
    }

    /**
     * 构造每一个按钮，并且可设置每个按钮的基本属性。如：图标大小，文字选中颜色和大小等。
     * {注意：此处如果设置了图标或文字的基本属性将取代以下全局设置的属性，如#setImgWidth}
     *
     * @param items 多个TabItem
     */
    public TabBar init(TabItem... items) {
        for (TabItem item : items) {//统一转换
            if (item.imgNormalId > 0) {
                item.imgNormal = ElementScatter.getInstance(getContext()).parse(item.imgNormalId);
            }
            if (item.imgActiveId > 0) {
                item.imgActive = ElementScatter.getInstance(getContext()).parse(item.imgActiveId);
            }
            if (item.descId > 0) {
                try {
                    item.desc = getResourceManager().getElement(item.descId).getString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        tabItems.addAll(Arrays.asList(items));
        TAB_NUM = tabItems.size();
        if (TAB_NUM <= 0) {
            throw new RuntimeException("Tab num must be greater than zero!");
        }
        return this;
    }

    /**
     * 底部栏背景样式
     */
    public TabBar setTabBackground(int xmlId) {
        backgroundElement = ElementScatter.getInstance(getContext()).parse(xmlId);
        return this;
    }

    /**
     * 底部栏背景样式
     */
    public TabBar setTabBackground(Element element) {
        backgroundElement = element;
        return this;
    }

    /**
     * 图标的宽度
     * {注意：如TabItem设置了，则会去掉本设置}
     */
    public TabBar setImgWidth(int size) {
        imgWidth = size;
        return this;
    }

    /**
     * 图标的高度
     * {注意：如TabItem设置了，则会去掉本设置}
     */
    public TabBar setImgHeight(int size) {
        imgHeight = size;
        return this;
    }

    /**
     * 字体大小
     * {注意：如TabItem设置了，则会去掉本设置}
     */
    public TabBar setTextSize(int size) {
        txtSize = size;
        return this;
    }

    /**
     * 字体正常颜色
     * {注意：如TabItem设置了，则会去掉本设置}
     */
    public TabBar setTextNormalColor(Color color) {
        txtNormalColor = color;
        return this;
    }

    /**
     * 字体选中颜色
     * {注意：如TabItem设置了，则会去掉本设置}
     */
    public TabBar setTextActiveColor(Color color) {
        txtActiveColor = color;
        return this;
    }

    /**
     * 按钮按下之后的回调
     */
    public TabBar setOnTabBarClickListener(OnTabBarClickListener listener) {
        this.listener = listener;
        return this;
    }


    /**
     * 生成并展示
     */
    public void create() {
        tabLayouts.clear();
        DirectionalLayout bottomTab = this;
        bottomTab.setBackground(backgroundElement);
        bottomTab.setOrientation(Component.HORIZONTAL);
        for (int index = 0; index < TAB_NUM; index++) {
            TabItem tabItem = tabItems.get(index);
            DirectionalLayout tab = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_tab, bottomTab, false);
            setItemLayout(index, tab, tabItem);

            tab.setClickedListener(component -> {
                DirectionalLayout curClick = (DirectionalLayout) component;
                if (selectLayout == curClick) {//已经上当前选中的了
                    return;
                }
                TabItem selectItem = null;
                curSelect = -1;
                for (int i = 0; i < TAB_NUM; i++) {
                    DirectionalLayout clickTab = tabLayouts.get(i);
                    TabItem clickItem = tabItems.get(i);
                    if (clickTab == curClick) {//当前点击的item
                        curSelect = i;
                        selectItem = clickItem;
                    }
                    setItemLayout(i, clickTab, clickItem);
                }
                if (listener != null) {//回调出去
                    listener.onClick(curSelect, curClick, selectItem);
                }
                selectLayout = curClick;
            });
            tabLayouts.add(tab);
            bottomTab.addComponent(tab);
        }
        invalidate();//请求重新绘制
    }

    //设置每个tab条目的样式
    private void setItemLayout(int index, DirectionalLayout tab, TabItem tabItem) {
        Image img = (Image) tab.findComponentById(ResourceTable.Id_bottom_tab_button_image);
        Text text = (Text) tab.findComponentById(ResourceTable.Id_bottom_tab_button_text);
        img.setWidth(tabItem.imgWidth > 0 ? tabItem.imgWidth : imgWidth);
        img.setHeight(tabItem.imgHeight > 0 ? tabItem.imgHeight : imgHeight);
        text.setTextSize(tabItem.txtSize > 0 ? tabItem.txtSize : txtSize);
        if (index == curSelect) {//选中状态
            if (tabItem.imgActive == null) {
                img.setVisibility(Component.HIDE);
            } else {
                img.setVisibility(Component.VISIBLE);
                img.setImageElement(tabItem.imgActive);
            }
            text.setTextColor(tabItem.txtActiveColor != null ? tabItem.txtActiveColor : txtActiveColor);
        } else {
            if (tabItem.imgNormal == null) {
                img.setVisibility(Component.HIDE);
            } else {
                img.setVisibility(Component.VISIBLE);
                img.setImageElement(tabItem.imgNormal);
            }
            text.setTextColor(tabItem.txtNormalColor != null ? tabItem.txtNormalColor : txtNormalColor);
        }

        if (tabItem.desc == null) {
            text.setVisibility(Component.HIDE);
        } else {
            text.setVisibility(Component.VISIBLE);
            text.setText(tabItem.desc);
        }
    }
}
